import React from 'react';
import { Form, Checkbox, Button, Row, Col, Card, Upload, Input } from 'antd';
import { connect } from 'dva';

import styles from './index.less';
const namespace = 'returnRoules';
// const { Step } = Steps;
/**
 *  登录界面
 */
@connect(({ loading, returnRoules }) => ({
  rouleId: returnRoules.rouleId,
  rulesDetail: returnRoules.rulesDetail,
  attachmentUrl: returnRoules.attachmentUrl,
  //控制状态，绑定事件
  submitting: loading.effects['login/doLogin']
  // returnRoules
}))
@Form.create()
class StepOne extends React.Component {
  state = {
    selectValue: [],
    noReturnablesList: [
      {
        id: 0,
        checked: false,
        name: 'Mattress'
      },
      {
        id: 1,
        checked: false,
        name: 'Fourdations'
      },
      {
        id: 2,
        checked: false,
        name: 'Patio furniture'
      },
      {
        id: 3,
        checked: false,
        name: 'Holiday products'
      },
      {
        id: 4,
        checked: false,
        name: 'Discount products'
      },
      {
        id: 5,
        checked: false,
        name: 'Customised products'
      },
      {
        id: 6,
        checked: false,
        name: 'Used goods'
      },
      {
        id: 7,
        checked: false,
        name: 'Gift cards'
      },
      {
        id: 8,
        checked: false,
        name: 'Grill'
      },
      {
        id: 9,
        checked: false,
        name: 'Assembled'
      },
      {
        id: 10,
        checked: false,
        name: 'Clearance final sale item'
      },
      {
        id: 11,
        checked: false,
        name: 'Toilets'
      },
      {
        id: 12,
        checked: false,
        name: 'Product category'
      }
    ],
    inputVisible: false,
    inputValue: '',
    indeterminate: false,
    checkAll: false //是否选中所有
  };
  showInput() {
    this.setState({
      inputVisible: true
    });
  }
  handleInputChange = e => {
    this.setState({ inputValue: e.target.value });
  };
  componentDidMount() {}

  handleInputConfirm = () => {
    const { inputValue } = this.state;
    let { noReturnablesList } = this.state;
    if (noReturnablesList && noReturnablesList.filter(item => item.name.indexOf(inputValue) === -1)) {
      this.state.noReturnablesList.push({
        id: noReturnablesList.length,
        checked: false,
        name: inputValue
      });
    }

    this.setState({
      noReturnablesList: this.state.noReturnablesList,
      inputVisible: false,
      inputValue: ''
    });
  };
  saveInputRef = input => (this.input = input);
  // 保存数据
  handleSubmit = (e, type) => {
    e.preventDefault();
    const { rulesDetail } = this.props;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        values.productsType = values.productsType.join(',');
        // if(type === "save"){//保存当前创建的数据
        //   this.props.dispatch({
        //     type: `${namespace}/save`,
        //     payload: {
        //       rulesDetail:{
        //         productsType:values.productsType,
        //       }
        //     }
        //   })
        // }else{
        //   this.props.dispatch({
        //     type: `${namespace}/save`,
        //     payload: {
        //       stepCurrent: 1,
        //       rulesDetail:{
        //         productsType:values.productsType,
        //       }
        //     }
        //   })
        // }
        this.props.dispatch({
          //更新规则
          type: `${namespace}/update`,
          payload: {
            productsType: values.productsType,
            id: rulesDetail ? rulesDetail.id : this.props.rouleId
          },
          callback: () => {
            if (type === 'save') return;
            this.props.dispatch({
              type: `${namespace}/save`,
              payload: {
                stepCurrent: 1
              }
            });
          }
        });
      }
    });
  };
  // 导入产品
  handleUpload(file) {
    const { rulesDetail } = this.props;
    this.props.dispatch({
      type: `${namespace}/importData`,
      payload: {
        file: file,
        id: rulesDetail ? rulesDetail.id : this.props.rouleId
      }
    });
  }
  // 下载Download attachment
  handleDownloadAttachment() {
    this.props.dispatch({
      type: `${namespace}/downloadAttachment`
    });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const { rulesDetail } = this.props;
    const { noReturnablesList, inputVisible, inputValue, indeterminate, checkAll } = this.state;

    return (
      <div className={styles.stepOne}>
        <Form onSubmit={this.handleSubmit}>
          <Card title="1 Add non-returnable products" bordered={false}>
            <Form.Item>
              {getFieldDecorator('checkAll', {
                initialValue:
                  rulesDetail &&
                  rulesDetail.productsType &&
                  rulesDetail.productsType.split(',').length >= this.state.noReturnablesList.length
                    ? true
                    : false
              })(
                <div>
                  <Checkbox
                    indeterminate={indeterminate}
                    onChange={e => {
                      let selectList = [];
                      if (e.target.checked) {
                        this.state.noReturnablesList.map(item => {
                          selectList.push(item.name);
                        });
                      } else {
                        this.setState({
                          selectValue: []
                        });
                      }

                      this.props.form.setFieldsValue({
                        productsType: selectList
                      });
                      this.setState({
                        indeterminate: false,
                        checkAll: e.target.checked,
                        selectValue: selectList
                      });
                    }}
                    checked={checkAll}
                  >
                    Select all
                  </Checkbox>
                </div>
              )}
            </Form.Item>
            <Form.Item>
              {getFieldDecorator('productsType', {
                rules: [{ required: true, message: 'Please select productsType!' }],
                initialValue: rulesDetail && rulesDetail.productsType ? rulesDetail.productsType.split(',') : []
              })(
                <Checkbox.Group
                  style={{ width: '100%' }}
                  onChange={checkedValue => {
                    console.log(checkedValue);
                    let array = [];
                    if (this.state.selectValue.filter(a => a === checkedValue).length > -1) {
                      array = this.state.selectValue.filter(a => a === checkedValue);
                      this.props.form.setFieldsValue({
                        productsType: array
                      });
                    } else {
                      this.state.selectValue.push(checkedValue);
                      array = this.state.selectValue;
                      this.props.form.setFieldsValue({
                        productsType: this.state.selectValue
                      });
                    }
                    this.setState({
                      selectValue: array
                    });
                  }}
                >
                  <Row>
                    {noReturnablesList.length > 0 &&
                      noReturnablesList.map(ditem => (
                        <Col span={6} key={ditem.id}>
                          <Checkbox value={ditem.name}>{ditem.name}</Checkbox>
                        </Col>
                      ))}
                    <Col span={6}>
                      {inputVisible ? (
                        <Input
                          ref={this.saveInputRef}
                          type="text"
                          size="small"
                          style={{ width: 78 }}
                          value={inputValue}
                          onChange={this.handleInputChange}
                          onBlur={this.handleInputConfirm}
                          onPressEnter={this.handleInputConfirm}
                        />
                      ) : (
                        <Button onClick={() => this.showInput()} className={styles.add}>
                          +Add others
                        </Button>
                      )}
                    </Col>
                  </Row>
                </Checkbox.Group>
              )}
            </Form.Item>
          </Card>
          <Card title="2 Set non-returnable SKUs" bordered={false}>
            {/* <h4>2 Set non-returnable SKUs</h4> */}
            <div className={styles.downUp}>
              <Upload showUploadList={false} customRequest={file => this.handleUpload(file)}>
                <Button>Upload attachment</Button>
              </Upload>
              <Button onClick={this.handleDownloadAttachment.bind(this)}>Download attachment</Button>
            </div>
            {this.props.attachmentUrl ? (
              <div>
                <a href={this.props.attachmentUrl} target="_blank" rel="noreferrer" style={{ color: 'blue' }}>
                  {this.props.attachmentUrl}
                </a>
              </div>
            ) : null}
          </Card>
          <Form.Item className={styles.btnList}>
            <Button onClick={e => this.handleSubmit(e, 'save')} className={styles.formBtn}>
              Save
            </Button>
            <Button htmlType="submit" className={styles.formBtn}>
              Next
            </Button>
          </Form.Item>
        </Form>
      </div>
    );
  }
}
export default StepOne;
